//
//  NetHandler.m
//  新建工程九
//
//  Created by 常宽 on 14-10-13.
//  Copyright (c) 2014年 常宽. All rights reserved.
//

#import "NetHandler.h"
#import <UIKit/UIKit.h>

@implementation NetHandler

+ (void)networkWithURL:(NSString *)urlStr completion:(void(^)(id result))block
{
    // 处理地址
    NSString *string = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:string];
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"get";
    
    //连接服务器 (block异步)
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        // 获取caches文件夹, 用来保存缓存数据
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        // 文件名的选择有两种: 第一种是接口的地址当文件名
        // 2.利用NSObject的哈希值(一个属性)
        
        NSInteger hash = [urlStr hash];
        NSString *filePath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.a", hash]];
        NSLog(@"cachesPath: %@", cachesPath);
        
        if (data != nil) {
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            
            // 将返回的结果,利用block传给外部使用的类
            
            block(result);
            
            // 在这里写入本地(NSData/NSDictionary)
            
            // 利用归档类 将data写入本地
            BOOL re = [NSKeyedArchiver archiveRootObject:data toFile:filePath];
            NSLog(@"请求数据缓存结果:%d", re);
            
        } else {
            NSLog(@"网络请求失败");
            // 在这里读取之前存储的数据
            
            NSData *dataRead = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            if (dataRead != nil) {
                NSError *error = nil;
                id resule = [NSJSONSerialization JSONObjectWithData:dataRead options:NSJSONReadingMutableContainers error:&error];
                NSLog(@"%@", resule);
                block(resule);
            } else {
                NSLog(@"无缓存");
                UIAlertView *warning = [[UIAlertView alloc]initWithTitle:@"网络故障" message:@"似乎已经断开了与网络的链接" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [warning show];
            }
        }
 
    }];

}

@end
